

import bpy
import math
import mathutils

from bpy_extras.io_utils import (ImportHelper,
									ExportHelper,
									path_reference_mode,
									axis_conversion,
									)
		
from bpy.props import BoolProperty
from bpy.props import EnumProperty
from bpy.props import StringProperty


import 物体.物体管理.物体数据 as 网格数据
import engine.initLIB.load_dll as engineLib
import ctypes









class Engine_ExportMM(bpy.types.Operator, ExportHelper):
	bl_idname = "export_scene.ms"
	bl_label = 'Export MS'
	bl_options = {'PRESET'}
	
	#filename_ext = StringProperty(subtype='FILE_PATH')
	filename_ext = '.ms'
	filepath = StringProperty(subtype='FILE_PATH')
	SelectOnly = BoolProperty(name="导出选定对象", description="导出选定对象", default=False)
	
	m_是否分割成三角形 = BoolProperty(default=True)

	def execute(self, context):
		#print('filepath', self.filepath, self.filename_ext, self.SelectOnly)
		m1 = mathutils.Matrix()
		m1 = m1.Rotation(math.radians(-90), 4, 'X')

		data = []
		for obj in bpy.data.objects:
			item = [(list(obj.type), list(obj.name))]
			#loc, rot, sca = 网格数据.f_变换矩阵_右手坐标系转左手坐标系(obj)

			mr = obj.rotation_euler.to_matrix()
			mr = mr.to_4x4()
			#mr = mr @  m1
			mr = m1 @  mr
			rot = list(mr.to_euler('XYZ'))
			print(' ===loc, rot, sca=== ', rot)
			#rot = list(obj.rotation_euler)
			rot[0] = math.degrees(rot[0])
			rot[1] = math.degrees(rot[1])
			rot[2] = math.degrees(rot[2])

			loc = list(m1 @ obj.location)
			#loc[1] = obj.location[2]
			#loc[2] = obj.location[1]

			sca = list(obj.scale)
			#sca[1] = obj.scale[2]
			#sca[2] = obj.scale[1]
			item.append([tuple(loc), tuple(rot), tuple(sca)])
			#print(' ====== ', [tuple(obj.location), tuple(obj.rotation_euler), tuple(obj.scale)])
			#print(' ===loc, rot, sca=== ', loc, rot, sca)
			if obj.type == 'MESH' :
				MESH = 网格数据.f_get物体网格数据(obj, context, 导出三角面=self.m_是否分割成三角形, 应用矩阵=False)
				item.append(MESH)
			elif obj.type == 'CAMERA':
				pass
			elif obj.type == 'LIGHT':
				pass

			data.append(item)
		engineLib.flexCAPI.f_save物体(ctypes.py_object(data), ctypes.py_object(list(self.filepath)))
		return {'FINISHED'}



def menu_func_export(self, context):
	self.layout.operator(Engine_ExportMM.bl_idname, text="场景文件 (.ms)")
	


classes = (
	Engine_ExportMM,
)
	
def register():
	for c in classes:
		bpy.utils.register_class(c)

	bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
	
def unregister():
	for c in classes:
		bpy.utils.unregister_class(c)

	bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)


